package com.hdl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.util.IOUtils;
import com.alibaba.fastjson.util.UTF8Decoder;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.io.IOException;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.UUID;

/**
 * 类名 RpcDecode
 * 描述 TODO
 *
 * @author hedonglin
 * @version 1.0
 * @date 2020/6/10 11:46
 */
public class RpcDecode extends ByteToMessageDecoder {
    private Class<?> clazz;

    private Serializer serializer;

    private String allMsg = "";

    public RpcDecode(Class<?> clazz, Serializer serializer) {
        this.clazz = clazz;
        this.serializer = serializer;
    }

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        System.out.println("decode invoke ");
        // 读取传送过来的消息的长度。
        int protoVersion = byteBuf.readShort();
        System.out.println("协议版本号：" + protoVersion);
        // 消息长度
        int msgLength = byteBuf.readShort();
        System.out.println("消息长度：" + msgLength);
        // 实际包大小
        int len = byteBuf.readableBytes();
        System.out.println("实际读取包长度:" + len);
        if (len < 1) {
            return;
        }
        try {
            byte[] bytes = new byte[len];
            if (byteBuf.isReadable()){
                byteBuf.readBytes(bytes);
                System.out.println(new String(bytes, StandardCharsets.UTF_8));
                Object o = serializer.deserialize(clazz, bytes);
                if (o != null){
                    System.out.println("解析数据为JSON成功");
                    list.add(o);
                }
                byteBuf.clear();
            }
        } catch (IOException e) {
            // 再次读取
            System.out.println("异常处理中-读取数据不是JSON");
            e.printStackTrace();
        }finally {

        }
    }

}
